//index.js
//获取应用实例
var app = getApp();
import Api from '../../api/api.js';
const api = new Api();
const APP_ID = "wx37eb4acd2fa366e2";
const APP_SECRET = '89d89133bb2079fc18c8a7b1162b860f';
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
  data: {
    headList: ["晒晒", "热门", "帮扶", "领养", "救助","种草","投票", "同城"],
    headHeigt:44,
    headTop:26,
    headWidht:317,
    l_top:30,
    tapSelectedIndex:0,
    hotList:[],
    isAuthorization:false,
    pageIndex:1,
    pageCount:10,
    dataList:[],
    serachText:"",
    isFirst:false,
    imageList:["/images/home/jb_add.png"],
    juBaoText:"",
    juBaoType:-1,
    itemId:-1,
    showJuBao:false,
    isShowJuBao:true,
    isShowMoreFloatView:false,
    navBarHeight:64,
  },
 
  onLoad: function () {
    var height = wx.getMenuButtonBoundingClientRect().height;
    var top = wx.getMenuButtonBoundingClientRect().top;
    var left = wx.getMenuButtonBoundingClientRect().left;
    var statausBarHeight = wx.getSystemInfoSync().statusBarHeight;
    var h =  statausBarHeight + height + (top - statausBarHeight) * 2;
    this.setData({
      navBarHeight:h,
      headHeigt: height,
      headTop:top,
      l_top: height - 15,
      headWidht:left - 20
    });
    this.getUserData();
    qqmapsdk = new QQMapWX({
      key: app.qqmapkey
    });
    this.beginGetHomeData();
   
  },
  onShow(){
    if (app.HOMENEEDFRESH){
      app.HOMENEEDFRESH = false;
      this.setData({
        tapSelectedIndex: 0
      });
      this.data.pageIndex = 1;
      this.getData();
    }
  },
  getHostList(){
    var _this = this;
    var map = {};
    map.pageCount = "4";
    map.pageIndex = "1";
    api.getRequestDataNoLoading(app.hostListUrl, map, false, "POST").then(res => {
      var list = res.list;
      _this.setData({
        hotList:list
      });

    });
  },
  beginGetHomeData(){
    var cityName = wx.getStorageSync("cityName");
    if (cityName) {
      this.data.isFirst = true;
      this.getData(cityName);
    } else {
      this.data.isFirst = false;
      this.getCurrentLoaction("");
    }
  },
  searchInput(e){
    this.data.serachText = e.detail.value;
  },
  searchData(){
    this.data.pageIndex = 1;
    this.getData();
  },
  getData(){  
    var _this = this;
    var text = this.data.headList[this.data.tapSelectedIndex];
    var kind = "1";
    if (text == "晒晒") {
      kind = 1;
    } else if (text == "救助") {
      kind = 2;
    } else if (text == "领养") {
      kind = 3;
    } else if (text == "帮扶") {
      kind = 4;
    } else if (text == "种草") {
      kind = 5;
    } else if (text == "投票") {
      kind = 6;
    } else if (text == "热门") {
      kind = 99;
    } else if (text == "同城") {
      kind = 88;
   
    } 
    var map = {};
    var city = wx.getStorageSync("cityName");
    map.city = city;
    map.key = _this.data.serachText;
    var user_id = wx.getStorageSync('USER_ID');
    if (!user_id) return;
    map.userId = app.USER_ID();
    map.kind = kind;
    map.pageCount = this.data.pageCount;
    map.pageIndex = this.data.pageIndex;
    api.getRequestData(app.postListUrl, map, true,"POST").then(res => {
      if (res.data.errorCode == 0) {
        _this.getHostList();
        var list = res.data.model.list;
        console.log("=====", JSON.stringify(list[0]));

        for (var i = 0; i < list.length; i++) {
          var dict = list[i];
          var content = dict.content;
          var contents = content.split("#");
          dict.contents = contents;
          var imgs = JSON.parse(dict.imgs);
          dict.imgs = imgs;
        }
        if (list.length == 0) {
          app.alert("没有更多数据了～");
        }
        if (_this.data.pageIndex == 1) {
          _this.data.dataList = list;
          _this.setData({
            dataList: _this.data.dataList
          });
        } else {
          // 加载更多
          _this.setData({
            dataList: _this.data.dataList.concat(list)
          });
        }
        if (_this.data.isFirst) {
          _this.data.isFirst = false;
          _this.getCurrentLoaction(city);
        }
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });

  },
  postItemClick(e){
    var index = e.currentTarget.dataset.key;
    var dict = this.data.dataList[index];
    var userId = dict.userId;
    var id = dict.id;
    var path = '/pages/index/detail/detail?USER_ID=' + userId + '&POST_ID=' + id;
    wx.navigateTo({
      url: path,
    })
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    this.data.pageIndex = 1;
    this.getData("");
  },
  onReachBottom: function () {
    this.data.pageIndex += 1;
    this.getData("");
  },
  followClick(e){
    var _this = this;
    var index = e.currentTarget.dataset.key;
    var item = this.data.dataList[index];
    var map = {};
    map.fanUserId = app.USER_ID();
    map.type = "5";
    if(app.USER_ID() == item.userId){
      app.alert("不能关注自己呀~");
      return;
    }
    map.userId = item.userId;
   
    api.getRequestData(app.userFansSaveUrl, map, false, "POST").then(res => {
      if (res.data.errorCode == 0) {
        app.showToasts("关注成功~");
        item.isFans = 1;
        _this.setData({
          dataList:_this.data.dataList
        });
        setTimeout(function(){
          _this.data.pageIndex = 1;
          _this.getData("");
        },1400);
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  canFollow(e) {
    var _this = this;
    var index = e.currentTarget.dataset.key;
    var item = this.data.dataList[index];
    wx.showModal({
      title: '提示',
      content: '确定不在关注?',
      confirmText: '确定',
      confirmColor: '#E97D6B',
      success: function (res) {
        if (res.confirm) {
          _this.cancelFollow(item);
        } else if (res.cancel) {
        }
      }
    });
  },
  cancelFollow(item) {
    var _this = this;
    var map = {};
    map.userId = app.USER_ID();
    map.userId2 = item.userId;
    api.getRequestData(app.deleteUserFansByUserId, map, false, "GET").then(res => {
      if (res.data.errorCode == 0) {
        app.alert("取消关注成功~");
        item.isFans = 0;
        _this.setData({
          dataList:_this.data.dataList
        });
        setTimeout(function(){
          _this.data.pageIndex = 1;
          _this.getData("");
        },1400);
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  getUserData(){
    var _this = this;
    app.getNewUserData().then(res => {
      _this.setData({
        isAuthorization: res
      });
      if (!res) {
        app.getOpenIdData().then(res => {
          _this.getData();
        });
      }
    });
  },
  
  headTapClick(e){
    var index = e.currentTarget.dataset.key;
    this.setData({
      tapSelectedIndex:index
    });
    this.data.pageIndex = 1;
    this.getData();
  },
  // 获取用户信息
  getNewUserInfo(e){
    var _this = this;
    app.getNewUserData().then(res => {
      _this.setData({
        isAuthorization: res
      });
      if (!res){
        app.getOpenIdData().then(res => {
          _this.getData();
        });
      }
    
    });
  },
  getCurrentLoaction: function (city) {
    var _this = this;
    wx.showLoading({
      title: '获取位置...',
    })
    wx.getLocation({
      type: "gcj02",
      success: function (res) {
        wx.hideLoading();
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            var result = addressRes.result;
            if (result) {
              var cityName = result.address_component.city;
              if (city != cityName){
                wx.setStorageSync("cityName", cityName);
                _this.getData(cityName);
              }
            }
          }, 
          fail(res) {

          }
        })
      },
      fail(res) {
        wx.hideLoading();

      }
    })
  },
  getOpenIdData(){
    var openId = wx.getStorageSync("OPEN_ID");
    var unionid = wx.getStorageSync("UNIONID");
    var userId = wx.getStorageSync("USER_ID");
    if (!openId || openId.length == 0 || !unionid || unionid.length == 0 || !userId || userId.length == 0) {
      app.getUnionIdAndOpenidData().then(res => {
      });
    } 
  },
  juBaoMoreClick(e){
    var key = e.currentTarget.dataset.key;
    this.data.itemId = key;
      this.setData({
        isShowMoreFloatView:true
      });
  },
  hiddenFloatView(){
    this.setData({
      isShowMoreFloatView:false
    });
  },
  collentPostClick(){
    this.hiddenFloatView();
    var _this = this;
    var map = {};
    map.contentId = this.data.itemId
    map.type = "5";
    map.userId = app.USER_ID();
    console.log("collentPostClick ======",JSON.stringify(map));

    api.getRequestData(app.postShouChangUrl, map, false, "POST").then(res => {
      _this.data.canEvaluate = true;
      if (res.data.errorCode == 0) {
        app.showToasts("收藏帖子成功～");
      } else {
        app.alert("res.data.errorMsg");
      }
    }).catch(err => { 
      _this.data.canEvaluate = true;
    });
  },
  juBaoHeClick(){
    this.hiddenFloatView();
    this.setData({
      isShowJuBao:true,
      showJuBao:true
    });
  },
 // 举报信息
 juBaoTextClick(e){
  var key = e.currentTarget.dataset.key;
  this.setData({
    juBaoType:key,
    isShowJuBao:false
  });
 },
 hiddenMoreView(){
  this.setData({
    showJuBao:false,
    isShowJuBao:true
  });
 },
 juBaoDetailInput(e){
  this.data.juBaoText = e.detail.value;
 },
 goToChooseImage(){
   var count = 7 - this.data.imageList.length;
   if (count <= 0){
     app.alert("最多只能传6张图片~");
     return;
   }
   var _this = this;
  app.chooseImageAndUpLoad(count).then(res=>{
    if (res){
      _this.setData({
        imageList:_this.data.imageList.concat(res)
      });
    }
  });
 },
 juBaoClick(){
  // 开始举报
    if (this.data.juBaoText.length == 0){
      app.alert("请输入举报详情~");
      return;
    }
    var _this = this;
    var map = {};
    map.content = this.data.juBaoText;
    var list = [];
    if (this.data.imageList.length > 1) {
      for (var i = 0;i < this.data.imageList.length;i++){
        if (i > 0) {
          list.push(this.data.imageList[i]);
        }
      }
    } 
    map.imgs = list;
    map.itemId = this.data.itemId
    map.itemType = "5";
    map.type = this.data.juBaoType;
    map.userId = app.USER_ID();
    api.getRequestData(app.juBaoSaveUrl, map, false, "POST").then(res => {
      _this.data.canEvaluate = true;
      if (res.data.errorCode == 0) {
        app.alert("举报提交成功～");
        _this.setData({
          showJuBao:false,
          isShowJuBao:true

        });
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }

    }).catch(err => { 
      _this.data.canEvaluate = true;
    });
  },
  goToMoreTopic(){
    wx.navigateTo({
      url: '/pages/index/huaTiList/huaTiList',
    })
  },
  topicPostClick(e){
    var id = e.currentTarget.dataset.key;
    wx.navigateTo({
      url: '/pages/index/huaTiList/postList?topicId=' + id,
    })
  },
  goToVoteDetial(e){
    var id = e.currentTarget.dataset.key;
    wx.navigateTo({
      url: '/pages/index/huaTiList/postList?topicId=' + id,
    })
  },
  loolUserPostList(e){
    var userId = e.currentTarget.dataset.key;
    wx.navigateTo({
      url: '/pages/mine/otherDetail/otherDetail?authorUserId='  + userId,
    })
  },
  onShareAppMessage: function () {
    return {
      title: '帖子分享',
      desc: '帖子分享',
      imageUrl:'',
      path: "/pages/index/index"
    }
   },
})
